﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.IO.IsolatedStorage;
using System.Xml.Serialization;
using System.Diagnostics;
using System.Collections.Generic;

namespace DeenGames.Utils
{
    public class XmlStorageProvider : IPersistentStorageProvider
    {
        // Used to access the actual storage
        private static IsolatedStorageFile isf;

        public XmlStorageProvider()
        {
            // Throws an exception if Isolated Storage is disabled
            isf = IsolatedStorageFile.GetUserStoreForApplication();
        }

        #region IPersistentStorageProvider Members

        public string Store<_type>(string key, _type value)
        {
            string newKey = PersistentStorageHelper.Hash(key) + ".dat";
            using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(newKey , System.IO.FileMode.Create, isf))
            {
                XmlSerializer ser = new XmlSerializer(value.GetType());
                ser.Serialize(stream, value);
            }
            return newKey;
        }

        public _type Retrieve<_type>(string key)
        {

            try
            {
                using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(PersistentStorageHelper.Hash(key) + ".dat", System.IO.FileMode.Open, isf))
                {
                    XmlSerializer ser = new XmlSerializer(typeof(_type));
                    return (_type)ser.Deserialize(stream);
                }

            }
            catch (IsolatedStorageException e)
            {
                Debug.WriteLine("Exception: " + e);
            }
            return default(_type);
        }

        public void Remove(string key)
        {
            string path = PersistentStorageHelper.Hash(key) + ".dat";
            try
            {
                isf.DeleteFile(path);
            }
            catch (IsolatedStorageException e)
            {
                Debug.WriteLine("Exception: " + e);
            }
        }

        public void Clear()
        {
            isf.Remove();
        }

        #endregion

        public IEnumerable<string> Keys
        {
            get
            {
                IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication();
                string[] names = isf.GetFileNames();
                foreach (string key in names)
                    yield return key;
            }
        }
    }
}
